{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "dimension = 400\n",
    "vocab = \"EOS abcdefghijklmnopqrstuvwxyz'\"\n",
    "char2idx = {char: idx for idx, char in enumerate(vocab)}\n",
    "idx2char = {idx: char for idx, char in enumerate(vocab)}\n",
    "\n",
    "def text2idx(text):\n",
    "    text = re.sub(r'[^a-z ]', '', text.lower()).strip()\n",
    "    converted = [char2idx[char] for char in text]\n",
    "    return text, converted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = 1\n",
    "PAD = 0\n",
    "EOS = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "train_X, train_Y = [], []\n",
    "text_files = [f for f in os.listdir('spectrogram-train') if f.endswith('.npy')]\n",
    "for fpath in text_files:\n",
    "    try:\n",
    "        splitted = fpath.split('-')\n",
    "        if len(splitted) == 2:\n",
    "            splitted[1] = splitted[1].split('.')[1]\n",
    "            fpath = splitted[0] + '.' + splitted[1]\n",
    "        with open('data/' + fpath.replace('npy', 'txt')) as fopen:\n",
    "            text, converted = text2idx(fopen.read())\n",
    "        w = np.load('spectrogram-train/' + fpath)\n",
    "        if w.shape[1] != dimension:\n",
    "            continue\n",
    "        train_X.append(w)\n",
    "        train_Y.append(converted)\n",
    "    except:\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_X, test_Y = [], []\n",
    "text_files = [f for f in os.listdir('spectrogram-test') if f.endswith('.npy')]\n",
    "for fpath in text_files:\n",
    "    with open('data/' + fpath.replace('npy', 'txt')) as fopen:\n",
    "        text, converted = text2idx(fopen.read())\n",
    "    w = np.load('spectrogram-test/' + fpath)\n",
    "    if w.shape[1] != dimension:\n",
    "        continue\n",
    "    test_X.append(w)\n",
    "    test_Y.append(converted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[0]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_layers,\n",
    "        size_layer,\n",
    "        learning_rate,\n",
    "        num_features,\n",
    "        dropout = 1.0,\n",
    "        beam_width=5, force_teaching_ratio=0.5\n",
    "    ):\n",
    "        \n",
    "        def lstm_cell(size, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size, initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.float32, [None, None, num_features])\n",
    "        self.label = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y_seq_len = tf.placeholder(tf.int32, [None])\n",
    "        self.Y = tf.sparse_placeholder(tf.int32)\n",
    "        seq_lens = tf.count_nonzero(\n",
    "            tf.reduce_sum(self.X, -1), 1, dtype = tf.int32\n",
    "        )\n",
    "        \n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        self.encoder_out = self.X\n",
    "\n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = lstm_cell(size_layer // 2),\n",
    "                cell_bw = lstm_cell(size_layer // 2),\n",
    "                inputs = self.encoder_out,\n",
    "                sequence_length = seq_lens,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            self.encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "            \n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        attention_mechanism = tf.contrib.seq2seq.LuongAttention(\n",
    "            num_units = size_layer, \n",
    "            memory = self.encoder_out,\n",
    "            memory_sequence_length = seq_lens)\n",
    "        \n",
    "        decoder_cell = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size_layer) for _ in range(num_layers)]),\n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        initial_state = decoder_cell.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        f, _ = tf.nn.dynamic_rnn(\n",
    "            decoder_cell,\n",
    "            self.X,\n",
    "            sequence_length=seq_lens,\n",
    "            initial_state=initial_state,\n",
    "            dtype=tf.float32)\n",
    "        \n",
    "        logits = tf.layers.dense(f, len(vocab))\n",
    "        time_major = tf.transpose(logits, [1, 0, 2])\n",
    "        decoded, log_prob = tf.nn.ctc_greedy_decoder(time_major, seq_lens)\n",
    "        decoded = tf.to_int32(decoded[0])\n",
    "        self.preds = tf.sparse.to_dense(decoded)\n",
    "        self.cost = tf.reduce_mean(\n",
    "            tf.nn.ctc_loss(\n",
    "                self.Y,\n",
    "                time_major,\n",
    "                seq_lens\n",
    "            )\n",
    "        )\n",
    "        self.optimizer = tf.train.AdamOptimizer(\n",
    "            learning_rate = learning_rate\n",
    "        ).minimize(self.cost)\n",
    "        \n",
    "        preds = self.preds[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        preds = pad_second_dim(preds, tf.reduce_max(self.Y_seq_len))\n",
    "        y_t = tf.cast(preds, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.label, masks)\n",
    "        self.mask_label = mask_label\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Logging before flag parsing goes to stderr.\n",
      "W0830 21:53:04.450350 139802294327104 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "W0830 21:53:04.465296 139802294327104 deprecation.py:323] From <ipython-input-6-9fffc4e17883>:17: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "W0830 21:53:04.468036 139802294327104 deprecation.py:323] From <ipython-input-6-9fffc4e17883>:37: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "W0830 21:53:04.469763 139802294327104 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "W0830 21:53:04.589721 139802294327104 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "W0830 21:53:05.260370 139802294327104 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "W0830 21:53:06.373947 139802294327104 lazy_loader.py:50] \n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "W0830 21:53:06.393591 139802294327104 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "W0830 21:53:06.672691 139802294327104 deprecation.py:323] From <ipython-input-6-9fffc4e17883>:51: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "W0830 21:53:07.765142 139802294327104 deprecation.py:323] From <ipython-input-6-9fffc4e17883>:64: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "W0830 21:53:07.801623 139802294327104 deprecation.py:323] From <ipython-input-6-9fffc4e17883>:67: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "\n",
    "size_layers = 512\n",
    "learning_rate = 1e-3\n",
    "num_layers = 2\n",
    "batch_size = 64\n",
    "epoch = 20\n",
    "\n",
    "model = Model(num_layers, size_layers, learning_rate, dimension)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "    train_X, dtype = 'float32', padding = 'post'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_X = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "    test_X, dtype = 'float32', padding = 'post'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens\n",
    "\n",
    "def sparse_tuple_from(sequences, dtype=np.int32):\n",
    "    indices = []\n",
    "    values = []\n",
    "\n",
    "    for n, seq in enumerate(sequences):\n",
    "        indices.extend(zip([n] * len(seq), range(len(seq))))\n",
    "        values.extend(seq)\n",
    "\n",
    "    indices = np.asarray(indices, dtype=np.int64)\n",
    "    values = np.asarray(values, dtype=dtype)\n",
    "    shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64)\n",
    "\n",
    "    return indices, values, shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:02<00:00,  3.47it/s, accuracy=0.777, cost=10.9]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  6.88it/s, accuracy=0.773, cost=11.8]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg cost 16.168093, training avg accuracy 0.692140\n",
      "epoch 1, testing avg cost 11.687258, testing avg accuracy 0.778333\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:01<00:00,  3.43it/s, accuracy=0.784, cost=10.9]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.64it/s, accuracy=0.781, cost=11.3]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg cost 11.270468, training avg accuracy 0.783225\n",
      "epoch 2, testing avg cost 11.564408, testing avg accuracy 0.773193\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:01<00:00,  3.33it/s, accuracy=0.871, cost=7.67]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.36it/s, accuracy=0.798, cost=12]  \n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg cost 9.437517, training avg accuracy 0.809655\n",
      "epoch 3, testing avg cost 12.459288, testing avg accuracy 0.793409\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:01<00:00,  3.40it/s, accuracy=0.892, cost=4.43]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.62it/s, accuracy=0.8, cost=14.2]  \n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg cost 6.191227, training avg accuracy 0.870010\n",
      "epoch 4, testing avg cost 15.361169, testing avg accuracy 0.797942\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:02<00:00,  3.35it/s, accuracy=0.957, cost=2.1] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.14it/s, accuracy=0.792, cost=18.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg cost 3.420565, training avg accuracy 0.927603\n",
      "epoch 5, testing avg cost 18.263155, testing avg accuracy 0.797635\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:02<00:00,  3.27it/s, accuracy=0.957, cost=1.81]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.46it/s, accuracy=0.802, cost=20]  \n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg cost 1.950696, training avg accuracy 0.959923\n",
      "epoch 6, testing avg cost 20.491978, testing avg accuracy 0.802584\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:04<00:00,  3.30it/s, accuracy=0.978, cost=1]    \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  6.87it/s, accuracy=0.796, cost=23.5]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg cost 1.169259, training avg accuracy 0.975812\n",
      "epoch 7, testing avg cost 22.987207, testing avg accuracy 0.802092\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:02<00:00,  3.40it/s, accuracy=0.971, cost=1.05] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.83it/s, accuracy=0.795, cost=23.8]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg cost 0.778768, training avg accuracy 0.984620\n",
      "epoch 8, testing avg cost 24.016600, testing avg accuracy 0.800943\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [01:00<00:00,  3.60it/s, accuracy=0.993, cost=0.355]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  8.19it/s, accuracy=0.798, cost=27.6]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg cost 0.623330, training avg accuracy 0.987652\n",
      "epoch 9, testing avg cost 25.809387, testing avg accuracy 0.802575\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.53it/s, accuracy=0.986, cost=0.389]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.60it/s, accuracy=0.795, cost=26.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg cost 0.528769, training avg accuracy 0.989543\n",
      "epoch 10, testing avg cost 26.889477, testing avg accuracy 0.801229\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.56it/s, accuracy=0.993, cost=0.479] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.87it/s, accuracy=0.792, cost=28.5]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg cost 0.339249, training avg accuracy 0.993332\n",
      "epoch 11, testing avg cost 28.172600, testing avg accuracy 0.802000\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.54it/s, accuracy=0.993, cost=0.294]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  6.37it/s, accuracy=0.792, cost=31]  \n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg cost 0.406057, training avg accuracy 0.991782\n",
      "epoch 12, testing avg cost 29.194811, testing avg accuracy 0.800685\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.55it/s, accuracy=0.971, cost=1.45]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  8.13it/s, accuracy=0.792, cost=29.4]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg cost 0.308338, training avg accuracy 0.993499\n",
      "epoch 13, testing avg cost 29.189384, testing avg accuracy 0.799171\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.57it/s, accuracy=0.971, cost=0.774]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  8.01it/s, accuracy=0.798, cost=29.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg cost 0.536825, training avg accuracy 0.989239\n",
      "epoch 14, testing avg cost 28.424778, testing avg accuracy 0.802677\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.50it/s, accuracy=0.878, cost=5.12]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  6.45it/s, accuracy=0.781, cost=19.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg cost 2.041507, training avg accuracy 0.960957\n",
      "epoch 15, testing avg cost 18.417307, testing avg accuracy 0.788410\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.56it/s, accuracy=0.986, cost=0.363] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.95it/s, accuracy=0.797, cost=22.7]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg cost 1.431114, training avg accuracy 0.969191\n",
      "epoch 16, testing avg cost 23.640419, testing avg accuracy 0.805068\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.59it/s, accuracy=0.993, cost=0.239] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.97it/s, accuracy=0.796, cost=27.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg cost 0.120194, training avg accuracy 0.998044\n",
      "epoch 17, testing avg cost 26.505846, testing avg accuracy 0.805741\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.50it/s, accuracy=0.993, cost=0.125] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.83it/s, accuracy=0.802, cost=28.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg cost 0.091450, training avg accuracy 0.998533\n",
      "epoch 18, testing avg cost 28.579634, testing avg accuracy 0.803484\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.60it/s, accuracy=1, cost=0.112]     \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.72it/s, accuracy=0.787, cost=30.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg cost 0.102293, training avg accuracy 0.998337\n",
      "epoch 19, testing avg cost 29.244181, testing avg accuracy 0.802551\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [00:58<00:00,  3.52it/s, accuracy=1, cost=0.149]     \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:01<00:00,  7.88it/s, accuracy=0.798, cost=29.8]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg cost 0.185908, training avg accuracy 0.996809\n",
      "epoch 20, testing avg cost 29.736197, testing avg accuracy 0.803046\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_cost, train_accuracy, test_cost, test_accuracy = [], [], [], []\n",
    "    for i in pbar:\n",
    "        batch_x = train_X[i : min(i + batch_size, len(train_X))]\n",
    "        y = train_Y[i : min(i + batch_size, len(train_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        _, cost, accuracy = sess.run(\n",
    "            [model.optimizer, model.cost, model.accuracy],\n",
    "            feed_dict = {model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        train_cost.append(cost)\n",
    "        train_accuracy.append(accuracy)\n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'testing minibatch loop')\n",
    "    for i in pbar:\n",
    "        batch_x = test_X[i : min(i + batch_size, len(test_X))]\n",
    "        y = test_Y[i : min(i + batch_size, len(test_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        cost, accuracy = sess.run(\n",
    "            [model.cost, model.accuracy],\n",
    "            feed_dict = {model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        \n",
    "        test_cost.append(cost)\n",
    "        test_accuracy.append(accuracy)\n",
    "        \n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    print('epoch %d, training avg cost %f, training avg accuracy %f'%(e + 1, np.mean(train_cost), \n",
    "                                                                      np.mean(train_accuracy)))\n",
    "    \n",
    "    print('epoch %d, testing avg cost %f, testing avg accuracy %f'%(e + 1, np.mean(test_cost), \n",
    "                                                                    np.mean(test_accuracy)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "real: say the word doll\n",
      "predicted: say the word wite\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "random_index = random.randint(0, len(test_X) - 1)\n",
    "batch_x = test_X[random_index : random_index + 1]\n",
    "print(\n",
    "    'real:',\n",
    "    ''.join(\n",
    "        [idx2char[no] for no in test_Y[random_index : random_index + 1][0]]\n",
    "    ),\n",
    ")\n",
    "batch_y = sparse_tuple_from(test_Y[random_index : random_index + 1])\n",
    "pred = sess.run(model.preds, feed_dict = {model.X: batch_x})[0]\n",
    "print('predicted:', ''.join([idx2char[no] for no in pred]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
